﻿using System.Collections.Generic;
using Autodesk.AutoCAD.DatabaseServices;
using ACADDatabase = Autodesk.AutoCAD.DatabaseServices.Database;
using JsonYNCNumsys.entity;

namespace JsonYNCNumsys
{
    /// <summary>
    /// 填写标题栏
    /// </summary>
    public class SetTitleDal
    {
        #region 属性
        /// <summary>
        /// 块属性/属性值链表.
        /// </summary>
        private List<BlockAttributeEntity> m_lstAtt;
        /// <summary>
        /// 块引用.
        /// </summary>
        BlockReference m_brf;
        /// <summary>
        /// 事务,为空表示操作当前图纸空间.
        /// </summary>
        private Transaction m_transaction;
        /// <summary>
        /// 图纸文档WorkingDatabase,为空表示当前的图纸空间.
        /// </summary>
        private ACADDatabase m_dataBase;
        /// <summary>
        /// 该值如果为True,则(1)m_transaction,m_dataBase;(2)事务提交在该类内完成.
        /// </summary>
        private bool m_TransactionIsUsed;
        #endregion

        public SetTitleDal(ACADDatabase wDataBase,Transaction tran,
            BlockReference brf, List<BlockAttributeEntity> lstAttr)
        {
            m_dataBase = wDataBase;
            m_transaction = tran;
            m_brf = brf;
            m_lstAtt = lstAttr;
            m_TransactionIsUsed = true;
        }
        public SetTitleDal(BlockReference brf, List<BlockAttributeEntity> lstAttr)
        {
            m_dataBase = HostApplicationServices.WorkingDatabase;
            m_transaction = null;
            m_brf = brf;
            m_lstAtt = lstAttr;
            m_TransactionIsUsed = false;
        }
        private void DoSetAttributeValue()
        {
            foreach (BlockAttributeEntity att in m_lstAtt)
            {
                string str_Tag = att.Tag;
                string str_TextString = att.TextString;
                foreach (ObjectId attId in m_brf.AttributeCollection)
                {
                    AttributeReference attRef = (AttributeReference)m_transaction.GetObject(attId, OpenMode.ForWrite, false);
                    Database oldDb = HostApplicationServices.WorkingDatabase;
                    HostApplicationServices.WorkingDatabase = attRef.Database;
                    if (attRef.Tag.ToUpper() == str_Tag)
                    {
                        attRef.TextString = str_TextString;
                        attRef.AdjustAlignment(attRef.Database);
                    }
                    HostApplicationServices.WorkingDatabase = oldDb;
                }
            }
        }
        public void Do()
        {
            if (!m_TransactionIsUsed)
            {
                using (m_transaction = m_dataBase.TransactionManager.StartTransaction())
                {
                    DoSetAttributeValue();
                    m_transaction.Commit();
                    m_transaction.Dispose();
                }
            }
            else
            {
                DoSetAttributeValue();
            }
        }
    }
}
